package com.x.erp.manage;

import com.x.erp.dao.InsuranceGoodsVoucherDao;
import com.x.erp.dao.InsuranceOrderGoodsDao;
import com.x.erp.model.InsuranceContract;
import com.x.erp.model.InsuranceOrder;
import com.x.erp.model.InsuranceOrderGoods;
import com.x.erp.util.ConstantState;
import com.x.framework.manage.BaseManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class InsuranceContractManage extends BaseManage {

	@Autowired
	private InsuranceOrderGoodsDao orderGoodsDao;

	@Autowired
	private InsuranceGoodsVoucherDao insuranceGoodsVoucherDao;

	/**
	 * 新增延保合同
	 */
	public InsuranceContract insertInsuranceContract(InsuranceContract insuranceContract, String orderId) throws Exception {
		Date cDate = new Date();
		insuranceContract.setContractCreateTime(cDate);
		insuranceContract.setContractUpdateTime(cDate);
		insuranceContract = this.insert(insuranceContract);
		InsuranceOrder insuranceOrder = new InsuranceOrder();
		insuranceOrder.setOrderId(orderId);
		// 订单状态变为使用中
		insuranceOrder.setOrderState(ConstantState.INSURANCE_ORDER_STATE_USING);
		insuranceOrder.setOrderUpdateTime(new Date());
		insuranceOrder.setContractId(insuranceContract.getContractId());
		this.update(insuranceOrder);
		// 为订单商品生成商品使用券
		createInsuranceGoodsVouchers(orderId);
		return insuranceContract;
	}

	// 为订单商品生成商品使用券
	private void createInsuranceGoodsVouchers(String orderId) throws Exception {
		InsuranceOrderGoods orderGoods = new InsuranceOrderGoods();
		orderGoods.setOrderId(orderId);
		List<InsuranceOrderGoods> orderGoodsList = orderGoodsDao.selectInsuranceOrderGoodsList(orderGoods);
		insuranceGoodsVoucherDao.insertVoucherList(orderGoodsList);
	}
}
